import time
import random
import signal
import os
import json
from xls import xls_file_to_json


def remove_file(filename):
    try:
        if os.path.exists(filename):  # 如果文件存在
            # 删除文件，可使用以下两种方法。
            os.remove(filename)
    except Exception as e:
        print(e)


def read_json_file(json_file, encoding="utf-8"):
    root = None
    with open(json_file, "r", encoding=encoding) as f:
        root = json.load(f)
    return root


# 生成[a, b)范围内随机数
def randFloat(a, b):
    return a + random.random() * (b - a)


# 从population列表中中随机取出一个元素
def randSample(population):
    return random.sample(population, 1)[0]


def main(filename, sensor_devices):
    remove_file(filename)
    # 计算时间戳
    timestamp = time.strftime("%Y/%m/%d %H:%M:%S")
    with open(filename, "w", encoding="utf-8") as f:
        # 生成的传感器数据个数[1, 10)
        n = len(sensor_devices)
        # 写入第1行
        f.write("time:{0}sensorunmber：{1}\n".format(timestamp, len(sensor_devices)))
        # 写入第2行
        f.write("%d\n" % n)
        # 开始传感器数据
        for sensor in sensor_devices:
            # print(sensor)
            sensor_id, sensor_catalog = sensor["id"], sensor["catalog"]
            # 要写入的数据
            data = None
            if sensor_catalog == "风速":
                # 第1列id  第2列value值   第3列传感器类型名
                data = ["%03d" % int(sensor_id), randFloat(0.15, 30), sensor_catalog]
            elif sensor_catalog == "风门开关":
                data = [
                    "%03d" % int(sensor_id),
                    randSample(["open", "close"]),
                    sensor_catalog,
                ]
            elif sensor_catalog == "压差":
                data = ["%03d" % int(sensor_id), randFloat(1500, 3000), sensor_catalog]

            if data != None:
                # 写入传感器数据
                # 注: 将data数组中的每个元素转换为str类型, 再构成一个新的字符串数组
                #     然后将每个字符串用\t隔开
                #     最后的得到的就是: '001\t1.4\t风速'
                f.write("\t".join([str(x) for x in data]) + "\n")
    print("[%s]%d个传感器数据更新" % (timestamp, n))


def register_exit_signal():
    def exit(signum, frame):
        # print("You choose to stop me.")
        os._exit(0)

    signal.signal(signal.SIGINT, exit)
    signal.signal(signal.SIGTERM, exit)


def read_test_sensor(filename):
    devices = []
    with open(filename, "r") as f:
        for line in f:
            devices.append(int(line.strip()))
    return devices


if __name__ == "__main__":
    register_exit_signal()
    # 读取传感器配置表格
    config = xls_file_to_json("./sensor_config.xls")
    # print(config)

    # 巡检周期、文件名
    cycle, filename = (
        config["monitor"]["cycle"],
        os.path.join(config["monitor"]["path"], config["monitor"]["filename"]),
    )
    # 正在使用的传感器
    is_valid_sensor = (
        lambda sensor: sensor["catalog"] != None
        and sensor["catalog"].strip() != ""
        and sensor["used"] != None
        and int(sensor["used"]) == 1
    )
    # sensor_devices = { id -> catalog}
    used_sensor_devices = [
        {"id": sensor["id"], "catalog": sensor["catalog"]}
        for sensor in config["devices"]
        if is_valid_sensor(sensor)
    ]

    while True:
        # 随机生成传感器数据
        main(filename, used_sensor_devices)
        # 按巡检周期, 定时生成数据文件
        time.sleep(cycle)
